var request=require('request');
var cheerio = require('cheerio');
var inquirer = require('inquirer');
const chalk = require('chalk');
const ora = require('ora');
const exec = require('child_process').exec;
var unirest = require("unirest");
const config = require('../config.json')
var COOKIE = config['gitlab-cookie'];
var TOKEN = config['gitlab-token'];
var configFn = require("./config");
var GIT_LIST = [];
let GIT_WAY = '';
const REMOTE_URL = 'www.gitlab.com';//写自己部署的gitlab项目地址

//获取git2项目列表
async function getGitList(){
    const spinner = ora(`正在从${REMOTE_URL}拉取列表...\n`).start();
    var currentPage = 1;
    var hasNext = true;
        while (hasNext) {
            let res = await getPageData(currentPage)
            currentPage = res.nextPage;
            hasNext = res.hasNext;
        }
    spinner.succeed(`拉取succeed!\n`);
}

//获取每页的git2项目列表
function getPageData(page){
    switch (GIT_WAY) {
        case 'token':
            return new Promise((resolve, reject)=>{
                const per_page=100;
                var options = {
                    'method': 'GET',
                    'url': `http://${REMOTE_URL}/api/v4/projects?private_token=${TOKEN}&order_by=last_activity_at&sort=desc&per_page=${per_page}&page=${page}`,
                };
                request(options, function (error, response) {
                    if (error){
                        console.log(chalk.red(`private_token连接不上 ${REMOTE_URL}`+error));
                        process.exit(0);
                    }
                    let list = JSON.parse(response.body);
                    list.forEach(i=>{
                        GIT_LIST.push({
                            name: i.path_with_namespace,
                            desc: i.description,
                            ssh_repo: i.ssh_url_to_repo,
                            branch: i.default_branch,
                        })
                    })
                    var hasNext = list.length===per_page;
                    var nextPage = page+1;
                    resolve({hasNext,nextPage})
                });
            });
    
        case 'cookie':
            return new Promise((resolve, reject)=>{
                var options = { 
                    method: 'GET',
                    json: true,
                    encoding: 'utf-8',
                    url: `http://${REMOTE_URL}/dashboard/projects/?non_archived=true&sort=latest_activity_desc&page=`+page,
                    headers: 
                    {  
                        cookie: COOKIE,
                    } 
                };
                request(options, function (error, response, body) {
                    //if (error) throw new Error(error);
                    if(response.statusCode===200){
                        var html = body.html;
                        const $ = cheerio.load(html,{ decodeEntities: false });
                        $('.projects-list .project-row .project-details').each(function(index,item){
                            var name= $(item).find('.project-full-name').text().replace(/\s+/g,"");
                            var desc= $(item).find('.description').text().replace(/\s+/g,"");
                            //console.log(name,desc);
                            GIT_LIST.push({
                                name,
                                desc,
                            })
                        })
                        var hasNext=$('.pagination').has('.js-next-button.disabled').length===0; //最后一页存在disabled
                        var nextPage=Number($('.active.page-item').text().replace(/\s+/g,""))+1;
                        resolve({hasNext,nextPage})
                    }else{
                        console.log(chalk.red(`连接不上 ${REMOTE_URL}`));
                        process.exit(0);
                    }
                });
            });
    }
        
    
}


/**
 * 获取Git详情数据
 * @param {*} gitName 
 */
async function getGitDetail(gitName){
    switch (GIT_WAY) {
        case 'token':
            return new Promise((resolve, reject)=>{
                const selectedOne = GIT_LIST.find(i=>i.name===gitName);
                resolve({
                    git_url: selectedOne.ssh_repo,
                    git_branch: selectedOne.branch,
                });
            }); 
    
        case 'cookie':
            return new Promise((resolve, reject)=>{
                var url=`http://${REMOTE_URL}/${gitName}`;
                var options = {
                    method: 'GET',
                    json: false,
                    encoding: 'utf8',
                    url: url,
                    headers: 
                    {  
                        'cache-control': 'no-cache',
                        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
                        'Accept-Encoding': 'br',
                        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
                        'Upgrade-Insecure-Requests': '1',
                        Connection: 'keep-alive',
                        'Content-Type': 'text/plain;charset=utf-8',
                        cookie: COOKIE,
                    } 
                };
                request(options, function (error, response, body) {
                    //if (error) throw new Error(error);
                    if(response && response.statusCode===200){
                        let html = fromHtmlGetBody(body);
                        const $ = cheerio.load(html,{ decodeEntities: false });
                        let git_url = $('#project_clone').val();
                        let git_branch = $('.project-refs-form .dropdown-toggle-text').text();
                        resolve({git_url,git_branch});
                    }else{
                        console.log(chalk.red(`打开git项目${gitName}失败`));
                        process.exit(0);
                    }
                });
            });  
    }
    
}
 
/**
 * 获取Git详情数据 - 这个版本用户参考，可以比较下 request 和 unirest 的差异
 * @param {*} gitName 
 */
async function getGitDetail2(gitName){
    return new Promise((resolve, reject)=>{
        var url = `http://${REMOTE_URL}/${gitName}`;
        var req = unirest("GET", url);
        req.headers({
        "Postman-Token": "0e27483f-bb6d-43ee-920e-e22ea45fc0cb",
        "cache-control": "no-cache",
        "Cookie": COOKIE,
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Accept-Encoding": "gzip, deflate",
        "Referer": `http://${REMOTE_URL}/`,
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
        "Upgrade-Insecure-Requests": "1",
        "Cache-Control": "no-cache",
        "Pragma": "no-cache",
        "Connection": "keep-alive"
        });
        req.end(function (response) {
            if(response.body){
                let html = fromHtmlGetBody(response.body);
                const $ = cheerio.load(html,{ decodeEntities: false });
                let git_url = $('#project_clone').val();
                let git_branch = $('.project-refs-form .dropdown-toggle-text').text();
                resolve({git_url,git_branch});
            }
        });
         
    });  
}

function fromHtmlGetBody(html){
    var rx = /<body[^>]*>([\s\S]+?)<\/body>/i;
    var body = rx.exec(html);
    if (body) body = body[1];
    return body;
}

function configIsNull(value){
    return value===null || value===undefined || value==='' ||  value==="''"
}

//主入口
async function list(cmd){
    if(cmd.token){
        GIT_WAY = 'token';
    }else if(cmd.cookie){
        GIT_WAY = 'cookie';
    }else if(!configIsNull(TOKEN)){
        GIT_WAY = 'token';
    }else if(!configIsNull(COOKIE)){
        GIT_WAY = 'cookie';
    }
    const answers = await inquirer.prompt([
        {
            type: 'rawlist',
            name: 'way',
            message: '您想用哪种方式访问git2 ?',
            choices: [{
                value:'token',
                name: `Personal Access Tokens (推荐)  请点击${chalk.blue(`http://${REMOTE_URL}/profile/personal_access_tokens`)}去创建token`,
            },{
                value:'cookie',
                name:'浏览器cookie   请打开浏览器控制台输入 document.cookie 获取',
            }],
            when: function (answers) {
                return GIT_WAY==='';
            },
        },
        {
            type:"input",
            message:"请输入token",
            name:'token',
            when: function (answers) {
                return (GIT_WAY||answers.way)==='token' && configIsNull(TOKEN);
            },
        },
        {
            type:"input",
            message:"请输入cookie",
            name:'cookie',
            when: function (answers) {
                return (GIT_WAY||answers.way)==='cookie' && configIsNull(COOKIE);
            },
        }
    ])
    if(answers.way){
        GIT_WAY = answers.way;
    }
    if(answers.token){
        TOKEN = answers.token;
        configFn({
            update: true,
            key: 'gitlab-token',
            value: TOKEN
        })
    }
    if(answers.cookie){
        COOKIE = answers.cookie;
        configFn({
            update: true,
            key: 'gitlab-cookie',
            value: COOKIE
        })
    }
    await getGitList();
    inquirer.prompt([
        {
            type:"rawlist",
            message:"请选择要下载的Git项目",
            name:'git',
            choices: GIT_LIST.map(i=>{
                return {
                    'value': i.name, // value不要加颜色
                    'name': chalk.hex('#3089DC')(i.name)+' '+i.desc
                }
            }),
            default:"",
            pageSize:20,
        },
    ]).then(async answers=>{
        const spinner = ora(chalk.green(`Start Clone...\n`));
        spinner.start();
        let gitFullName = answers.git;
        let { git_url, git_branch } = await getGitDetail(gitFullName);
        let git_name = gitFullName.split('/')[1];
        let cmdStr = `git clone ${git_url} && cd ${git_name} && git checkout ${git_branch}`;
        exec(cmdStr, (error, stdout, stderr) => {
            if (error) {
                spinner.fail(chalk.red(error))
                process.exit()
            }
            spinner.succeed(chalk.green(`Clone completed!√\n`));
            process.exit()
        })
               
    })
}
module.exports = list;